﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using System.Globalization;
using System.Web.UI.WebControls;
using Widgetsphere.Autos.Websitev2.Objects;
using Widgetsphere.Autos.API.FacetedNavigation;
using HP.Datastore.Common;

namespace Widgetsphere.Autos.Websitev2.UserControls
{

    #region DimensionDisplayEventArgs

    public class DimensionDisplayEventArgs : EventArgs
    {
        #region Class Members

        private ListingQuery _query = null;
        private RefinementItem _refinement = null;

        #endregion

        #region Constructors

        public DimensionDisplayEventArgs(ListingQuery query, RefinementItem refinement)
        {
            _query = query;
            _refinement = refinement;
        }

        #endregion

        #region Property Implmentations

        public ListingQuery Query
        {
            get { return _query; }
        }

        public RefinementItem Refinement
        {
            get { return _refinement; }
        }

        #endregion

    }

    #endregion

    public abstract class DimensionDisplayControl : System.Web.UI.UserControl
    {
        #region Class Members

        private int _itemsPerRow = 3;
        private int _maxItems = 0;
        private string _moreLinkText = "";
        private string _moreLinkURL = "";
        private string _suffix = "";
        private bool _allowCount = true;
        private bool _allowWidth = true;
        private bool _alignColumns = true;
        private ListingResults _queryResults = null;

        #endregion

        #region Events

        public event EventHandler<DimensionDisplayEventArgs> LinkSetup;

        protected void OnLinkSetup(DimensionDisplayEventArgs e)
        {
            if (this.LinkSetup != null)
                this.LinkSetup(this, e);
        }

        #endregion

        #region Property Implementations

        public int ItemsPerRow
        {
            get { return _itemsPerRow; }
            set { _itemsPerRow = value; }
        }

        public int MaxItems
        {
            get { return _maxItems; }
            set { _maxItems = value; }
        }

        public string MoreLinkText
        {
            get { return _moreLinkText; }
            set { _moreLinkText = value; }
        }

        public string MoreLinkURL
        {
            get { return _moreLinkURL; }
            set { _moreLinkURL = value; }
        }

        public string Suffix
        {
            get { return _suffix; }
            set { _suffix = value; }
        }

        public bool AllowCount
        {
            get { return _allowCount; }
            set { _allowCount = value; }
        }

        public bool AllowWidth
        {
            get { return _allowWidth; }
            set { _allowWidth = value; }
        }

        public bool AlignColumns
        {
            get { return _alignColumns; }
            set { _alignColumns = value; }
        }

        public ListingResults QueryResults
        {
            get { return _queryResults; }
        }

        #endregion

        #region Methods

        protected abstract PlaceHolder MorePanel { get; }
        protected abstract Table MainTable { get; }

        public virtual void Populate(DimensionItem dItem, bool isLimited)
        {
            try
            {
                var index = 0;

                //Round down to even multiple of ItemsPerRow
                var maxItems = this.MaxItems;
                if (maxItems > 0) maxItems = maxItems - (maxItems % ItemsPerRow);
                if (maxItems == 0) maxItems = dItem.RefinementList.Count;

                //Make names title case
                var cultureInfo = Thread.CurrentThread.CurrentCulture;
                var textInfo = cultureInfo.TextInfo;

                if (dItem.RefinementList.Count == 0)
                {
                    this.Visible = false;
                    return;
                }

                foreach (RefinementItem rItem in dItem.RefinementList.OrderBy(x => x.MinValue).ThenByDescending(x => x.Count).Take(maxItems).OrderBy(x => x.FieldValue))
                {
                    TableRow row = null;
                    if (index%this.ItemsPerRow == 0)
                    {
                        if ((index == maxItems) && (maxItems > 0))
                        {
                            //Add the more link if necessary
                            if (this.MoreLinkText != string.Empty && this.MoreLinkURL != string.Empty)
                            {
                                var l = new Literal();
                                l.Text = "<div align=\"right\"><a href=\"" + this.MoreLinkURL + "\" title=\"" + this.MoreLinkText + "\">" + this.MoreLinkText + "</a></div>";
                                this.MorePanel.Controls.Add(l);
                            }
                            return;
                        }
                        row = new TableRow();
                        if (!this.AlignColumns)
                        {
                            //If we are NOT aligning columns then there will be one column in each row so create it
                            row.Cells.Add(new TableCell());
                        }

                        this.MainTable.Rows.Add(row);
                    }
                    else
                    {
                        row = this.MainTable.Rows[this.MainTable.Rows.Count - 1];
                    }

                    var query2 = new ListingQuery("/auto-results.aspx");
                    this.OnLinkSetup(new DimensionDisplayEventArgs(query2, rItem));

                    //Create the link
                    var link = new Literal();
                    var linkText = textInfo.ToTitleCase(rItem.FieldValue.ToLower());
                    if (this.Suffix != "") linkText += " " + this.Suffix;
                    if (this.AllowCount) linkText += " (" + rItem.Count.ToString("###,###,###,##0") + ")";
                    if (query2.NonParsedFieldList.Count > 0)
                        link.Text = "<a href=\"" + query2.ToString() + "\" title=\"" + linkText + "\">" + linkText + "</a>";
                    else
                        link.Text = "<a href=\"" + query2.ToFormattedString() + "\" title=\"" + linkText + "\">" + linkText + "</a>";

                    if (this.AlignColumns)
                    {
                        //This is all inside of a table with multiple columns
                        var cell = new TableCell();
                        if (this.AllowWidth)
                        {
                            this.MainTable.Width = new Unit(100, UnitType.Percentage);
                            if (index < ItemsPerRow) cell.Width = new Unit((int) (100/ItemsPerRow), UnitType.Percentage);
                        }
                        row.Cells.Add(cell);
                        cell.Controls.Add(link);
                    }
                    else
                    {
                        //The table has one column per row and 
                        var cell = row.Cells[0];
                        if (this.AllowWidth)
                        {
                            this.MainTable.Width = new Unit(100, UnitType.Percentage);
                            if (index < ItemsPerRow) cell.Width = new Unit((int) (100/ItemsPerRow), UnitType.Percentage);
                        }
                        cell.Controls.Add(link);
                    }

                    index++;
                }

            }
            catch (Exception ex)
            {
                throw;
            }
        }

        #endregion

    }
}